<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="org.apache.shiro.SecurityUtils" %>
<%@ page import="com.topisv.tms.service.account.ShiroDbRealm.ShiroUser" %>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
<script type="text/javascript">
  
  var dataTables_handled;   //dataTables-已发货订单 
  
  $(function() {
		$("#queryForm").validate(); 
		//初始化日期选择框
		$("#_dataRange").daterangepicker({
            format: 'YYYY-MM-DD',
	        dateLimit:{days : 30}
		});
		var now = new Date();
		var today=(now.getFullYear())+"-"+(now.getMonth()<10? "0"+(now.getMonth()+1):now.getMonth())+"-"+(now.getDate()<10? "0"+now.getDate():now.getDate());
		$("#_dataRange").val(today+" - "+today);
		
		initTable();
		
		$('#myCheckedAll').on('ifChecked', function(event){
	    	// alert(event.type + ' callback');
		    $("input[name='single_myChecked']").iCheck('check');
	    });
		$('#myCheckedAll').on('ifUnchecked', function(event){
    		// alert(event.type + ' callback');
	    	$("input[name='single_myChecked']").iCheck('uncheck');
    	});
    });
  
    function initTable(){
      dataTables_handled=$("#table_handled").dataTable({
         "bServerSide":true,
         "scrollX": true,
         "sAjaxSource":'${ctx}/outstorageBill/queryQMResendInfo',
         "fnServerData": resendDataQuery,
         "fnInitComplete": tableInitComplete,
         "aLengthMenu": [[10, 25, 50, 100, 500, 1000], ["10", "25", "50", "100", "500", "1000"]],// 前面是具体数值，-1表示全部，后面是前端显示的信息
         "bFilter": false,
         "bSort": false,
         "sZeroRecords": "查询无记录！",
         "bProcessing": true,
         "oLanguage": {
             "sUrl": '${ctx}/static/v2/js/plugins/datatables/cn.txt'
          },
          "aoColumns": [
                  { "mData": 'relatedNo',
                    "sDefaultContent": "",
                    "render":function(obj){
                      return "<input type='checkbox' name='single_myChecked' id='single_" + obj +"' value='"+obj+"' />";
                    }
                  },
                  { "mData": null,
                    "sDefaultContent": "",
                  	 "mRender": function (data, display, row) {
	              		<c:forEach items="${customerList}" var="customer">
							if("${customer.customerCode}" == row.customerCode){
								return "<font class='customerName' value='${customer.customerCode}'>${customer.customerName}</font>";
							}
						</c:forEach>
						return "";
		           }
                  },
                  {
                    "mData": 'relatedNo',
                    "sDefaultContent": "",
                    "render":function(obj){
                      return "<a href='${ctx}/orderMsg/v2_orderMsgDetail/"+obj+"' title='查看订单信息' target='_blank'>"+obj+"</a>";
                    }
                  },
                  {"mData": 'customerOrderno',
                   "sDefaultContent": ""},
                  {"mData": 'fromno',
                   "sDefaultContent": ""},
                  {"mData": 'expressNo',
                   "sDefaultContent": "",
                   "render":function(obj,type,full){
                     console.log(obj);
                     console.log(type);
                     console.log(full);
                   	return full.expressNo||full.ebillNo;
                   }
                  },
                  {
                    "mData": 'billType',
                    "sDefaultContent": "",
                    "render": function (obj) {
                       var billType=obj;
                       if(billType=='cbill'){
                         return "普通面单";
                       }else if(billType=='ebill'){
                         return "电子面单";
                       }else{
                         return "";
                       }
                    }
                  },
                  {"mData": 'warehouseCode',
                   "sDefaultContent": ""},
                  {"mData": 'batchCode',
                   "sDefaultContent": "",
                   "render":function(obj){
                          return "<a href='${ctx}/workMsg/v2_workMsgDetail/"+obj+"' title='查看批次信息' target='_blank'>"+obj+"</a>";
                    }
                  },
                  {
                    "mData": 'cancelStatus',
                    "sDefaultContent": "",
                    "render": function (obj) {
                       var cancelStatus=obj;
                       if(cancelStatus=='ok'){
                         return "正常单";
                       }else if(cancelStatus=='cancel'){
                         return "<font color=red>取消单</font>";
                       }else if(cancelStatus=='refuse'){
                         return "<font color=red>拒收单</font>";
                       }else if(cancelStatus=='change'){
                         return "<font color=red>换货单</font>";
                       }else if(cancelStatus=='outScope'){
                         return "<font color=red>超区件</font>";
                       }else if(cancelStatus=='lose'){
                         return "<font color=red>丢件单</font>";
                       }else{
                         return "";
                       }
                    }
                  },{
                    "mData": 'status',
                    "sDefaultContent": "",
                    "render": function (obj) {
                       var status=obj;
                       if(status=='1'){
                         return "创建批次";
                       }else if(status=='2'){
                         return "创建任务";
                       }else if(status=='3'){
                         return "已拣货";
                       }else if(status=='4'){
                         return "已灯光拣选";
                       }else if(status=='5'){
                         return "待包装";
                       }else if(status=='6'){
                         return "已发货";
                       }else if(status=='9'){
                         return "待包装";
                       }else if(status=='0'){
                         return "待创建批次";
                       }else{
                         return "";
                       }
                    }
                  },{
                    "mData": null,
                    "sDefaultContent": "",
                    "render":function(data, display, row){
                        return "<button class='btn btn-primary resendBtn' onclick=\"ajaxResend('" + row.relatedNo + "','" + row.customerCode + "')\">重新回传</button>";
                	  }
                  }
           ]
      });
    }
  
	function tableInitComplete(oSettings, json) {
	  $("input[name='single_myChecked']").iCheck({
	    checkboxClass: 'icheckbox_minimal',
	  });
	}
  
  	function ajaxResend(orderNos,customerCodes){
  	    // $btn.removeAttr("class").addClass('btn disabled bind');
    	// $btn.removeAttr("style").attr("style","background-color: gray");
  	    $('.resendBtn').attr("disabled",true);
  	    var orderNoArr = new Array();
  	    var customerCodeArr = new Array();
  	    if((orderNos instanceof Array) && (customerCodes instanceof Array)){
  	      orderNoArr = orderNos;
  	      customerCodeArr = customerCodes;
  	    } else {
  	      orderNoArr[0] = orderNos;
  	      customerCodeArr[0] = customerCodes;
  	    }
  	    $.ajax({
			type : 'post',
			url : '${ctx}/outstorageBill/outstorageBillQMResend',
			data : {
			    "orderNos":orderNoArr,
			    "customerCodes":customerCodeArr
			},
			dataType : 'json',
			success : function(data) {
			  	if(data.state="success"){
			    	alert("共重发数量：" + data.sum + "，成功：" + data.successNum + "，失败：" + data.failureNum + "，未接入：" + data.undoNum);
			  	}else{
			  	  	alert(data.msg);
			  	}
			    $('.resendBtn').attr("disabled",false);
			},
			error : function(data) {
				console.log(data);
				alert("网络异常，请稍后再试...");
			}
		});
  	}
  	
	//查询
	function query(){
	   //商家：
	   var customerCode=$("#_customerCode").val();
	   //日期：
	   var dataRange=$("#_dataRange").val();
	   if(dataRange.length==0){
	      alert("请选择日期范围...");
	      return;
	   }
	   if(dataTables_handled)
	     dataTables_handled.fnDestroy();
	   initTable();
	}
	
	function resendDataQuery( sSource, aoData, fnCallback ) {
	   var queryData = [];
	   //查询参数
	   var dataRange=$("#_dataRange").val();
	   var times=dataRange.split(" - ");
	   queryData.push({ "name":"fromTime", "value": times[0]});
	   queryData.push({ "name":"toTime", "value": times[1]});
	   var customerCode=$("#_customerCode").val();
	   queryData.push( { "name": "customerCode", "value": customerCode } );
	   var warehouseCode=$("#_warehouseCode").val();
	   queryData.push( { "name": "warehouseCode", "value": warehouseCode } );
	   var orderno=$("#_orderno").val();
	   queryData.push( { "name": "relatedNo", "value": orderno } );
	   var status=$("#_status").val();
	   queryData.push( { "name": "status", "value": status } );
	   var data = arrayToJson(aoData.concat(queryData));
	   $.ajax({ 
	       "type": "post",
	       "url": sSource,    
	       "dataType": "json",   
	       "data": data,
	       "success": function(resp) {  
	       			fnCallback(resp);
	       			$("#total_handled").html("("+resp.iTotalRecords+")");
	       		}
	   });    
	}
	
	/**
    *	将json数组转换为json对象
    */
   function arrayToJson(array) {
   	var jsonParam = {};
       for (var i = 0; i < array.length; i++) {
       	jsonParam[array[i].name] = array[i].value;
     	}
     	return jsonParam;
 	}
	
	function ajaxAreaGroup2(id) {
	    $("#"+id).html('');
		var customerCode = $('#_customerCode').val();
		if(customerCode==''){
		  return false;
		}
		$.ajax({
				type : 'post',
				url : path+'/areaGroup/ajaxAreaGroup',
				data : 'customerCode=' + customerCode,
				dataType : 'json',
				success : function(data) {
				  var tempString="";
				  tempString+="<option value=''></option>";
					if (data.status == "1") {
						$.each(data.content,function(i){
						    tempString+="<option value="+data.content[i].groupCode+">"+data.content[i].groupName;
						});
					}else if (data.status == "2") {
						$.each(data.content.restAreaGroupDtos,function(i){
						    tempString+="<option value="+data.content.restAreaGroupDtos[i].areagroupCode+">"+data.content.restAreaGroupDtos[i].areagroupName;
						});
					} else {
						alert(data.content);
					}
	                  $("#"+id).html(tempString);
	                  $("#"+id).trigger("chosen:updated");
				},
				error : function() {
					alert("获取信息错误！");
				}
			});
	}
	
	function batchResend(){
	    // $("#single_PD1471592823775123").prop("checked")
	    var orderNos = new Array();
	    var customers = new Array();
	    $("input[name='single_myChecked']").each(function(){
	      if($(this).prop("checked")){
	        orderNos.push($(this).val());
	        customers.push($(this).closest('tr').find('.customerName').attr("value"));
	        // orderNos += $(this).val() + ",";
	      }
	    });
	    if(orderNos.length <1){
	      alert("请在需要回传的行前打勾!");
	      return;
	    } else{
	      ajaxResend(orderNos,customers);
	    }
	}
	
</script>
</head>
<body>
<section class="content">
    <!-- 查询条件  start-->
   	<div class="row">
	<div class="col-md-12">
			<!-- Primary box -->
			<div class="box box-solid box-primary" >
			    
				<div class="box-header">
					<i class="fa fa-search"></i>
					<h3 class="box-title">搜索栏</h3>
				</div>
				
				<div class="box-body">
				    <form class="form-search" id="queryForm" method="post" >
				    <!-- 第一行 -->
					<div class="form-group row">
					
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 商家： </span> 
								<select data-placeholder="请选择..." class="form-control searchSelect" id="_customerCode" name="_customerCode" onchange="ajaxAreaGroup2('_warehouseCode')">
									<option value=""></option>
									<c:forEach items="${customerList}" var="customer">
										<option value="${customer.customerCode}"
											<c:if test="${customerCode eq customer.customerCode}">selected=selected</c:if>>${customer.customerName}</option>
									</c:forEach>
								</select>
							</div>
						</div>
						
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 仓库： </span> 
								<select data-placeholder="请选择商家..." class="form-control span3" id="_warehouseCode" name="_warehouseCode">
									<option value=""></option>
									<c:forEach items="${warehouseList}" var="warehouse">
										<option value="${warehouse.groupCode}" >${warehouse.groupName}</option>
									</c:forEach>
								</select>
							</div>
						</div>
						
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 订单编号： </span> 
								<input type="text" class="form-control" id="_orderno" name="_orderno">
							</div>
						</div>
						
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text">回传状态:</span>
								<select  class="form-control" id="_status" name="_status" >
									<option value="">全部</option>
							        <option value="FINISH">回传成功</option>
							        <option value="ERROR">回传失败</option>
								</select>
							</div>
						</div>
						
					</div>

                    <!-- 第二行 -->
					<div class=" form-group row">

						<div class="col-sm-6">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 日期范围： </span>

								<div class="input-group">
									<div class="input-group-addon">
										<i class="fa fa-calendar"></i>
									</div>
									<input type="text" class="form-control pull-right" id="_dataRange" name="_dataRange" value="${param._fromDate}"/>
								</div>
								
							</div>
						</div>
						
					</div>
					 <!-- 第三行 -->
					<div class=" form-group row">
						<div class="col-sm-1">
								<button class="btn btn-primary" type="button" onclick="query();">搜索</button>
						</div>
						<div class="col-sm-1">
								<button class="btn btn-primary resendBtn" type="button" onclick="batchResend();">批量重发</button>
						</div>
					</div>
					</form>
				</div>

			</div>

	 </div>
	</div>
    <!-- 查询条件 end -->
  
    <!-- 查询结果 start -->
   	<div class="row">
	<div class="col-md-12">
			<!-- Primary box -->
			<div class="box box-solid box-primary" >
    <div class="box-header">
		<i class="fa fa-list"></i>
		<h3 class="box-title">查询结果</h3>
	</div>
    
	<div class="form-group row" >
	<div class="col-md-12">
		<!-- 已发货订单 start --> 
		                 <div class="box">
		<div class="box-header"></div>
		<div class="box-body table-responsive">
		    <table id="table_handled" class="table table-bordered table-striped">
		        <thead>
		            <tr>
		            	<th><input type="checkbox" name="single_myCheckedAll" id="myCheckedAll" /></th>
		               	<th>商家</th>
						<th>能容订单号</th>
						<th>商家订单号</th>
						<th>来源订单号</th>
						<th>快递单号</th>
						<th>运单类型</th>
						<th>仓库</th>
						<th>作业批次号</th>
						<th>订单状态</th>
						<th>作业状态</th>
						<th>操作</th>
					</tr>
				</thead>
		     </table>
		 </div>
		</div>
		<!-- 已发货订单 end -->
	</div>
	</div>
	</div>
	</div>
	</div>
	<!-- 查询结果 end -->
	
	</section>
</body>
</html>